import axios from "axios";
import qs from "qs";
import { ElMessage } from "element-plus";
import stroe from "@/store/index.js";
import store from "../store";
import { showLoading, hideLoading } from "@/utils/loading.js";
import router from "@/router";

const uploadServer = "http://192.168.1.25:9555/"; //文件上传地址
// const uploadServer = "http://192.168.1.25:8010/"; //文件上传地址

const apiObj = {
  pro: {
    api: "/api",
  },
  dev: {
    api: "/api1",

    // api: "http://192.168.1.15:9090/"
    // api: "http://192.168.1.25:9090/"
    // api:"https://www.goaldice.com/api/"
    // api:"https://www.goaldice.com/api/"
    // api: "http://192.168.1.25:8009/"
  },
};

// const currentObj = apiObj.pro.api; //正式/
const currentObj = apiObj.dev.api; //測試
// const currentObj = "http://partner.nesensor.com/source/main"

const service = axios.create({
  baseURL: currentObj,
  timeout: 60000,
  headers: {
    Authorization: "Basic c2FiZXI6c2FiZXJfc2VjcmV0",
  },
});

// 请求拦截
service.interceptors.request.use(
  (config) => {
    //console.log(config);
    // showLoading();
    // 登录接口请求头为表单 其他为默认application/json
    if (config.url == "/user/login") {
      config.headers["content-type"] = "application/x-www-form-urlencoded";
      config.data = qs.stringify(config.data);
    }

    // 用户登录请求携带token
    if (store.state.accessToken) {
      config.headers["blade-auth"] = "bearer " + store.state.accessToken;
    }

    return config;
  },
  (err) => {
    hideLoading();
    return Promise.reject(err);
  }
);

// 响应拦截
let showErrorTitle = true;
service.interceptors.response.use(
  (res) => {
    hideLoading();
    //console.log(res.status);
    if (
      res.data.code == 0 ||
      res.code == 0 ||
      res.data.code == 2 ||
      res.data.code == 3 ||
      res.data.repCode == "0000"
    ) {
      //console.log(res.data,'123')
      return Promise.resolve(res.data);
    } else if (res.data.code == 401) {
      hideLoading();
      if (store.state.accessToken && showErrorTitle) {
        showErrorTitle = false;
        ElMessage.error("登录过期,请重新登录!");
        store.commit("outLogin");
        router.push("/");
        setTimeout(() => {
          showErrorTitle = true;
        }, 3000);
      }
      return Promise.reject(res.data);
    } else if (res.data.code == 1) {
      ElMessage.error(res.data.message);
      return Promise.reject(res.data);
    } else {
      return Promise.reject(res.data);
    }
    // return res;
  },
  (err) => {
    hideLoading();
    ElMessage.error("访问量过大,请稍后再试");
    return Promise.reject(err);
  }
);

// export default service;
export { service, uploadServer };
